﻿using System;
using System.Collections.Generic;
using Me.Prettyprint.Cassandra.Serializers;
using Me.Prettyprint.Cassandra.Service;
using Me.Prettyprint.Cassandra.Utils;
using Me.Prettyprint.Hector.Api;
using Me.Prettyprint.Hector.Api.Beans;
using Me.Prettyprint.Hector.Api.Factory;
using Me.Prettyprint.Hector.Api.Query;
using Org.Apache.Cassandra.Thrift;

namespace Me.Prettyprint.Cassandra.Model.Thrift
{
    /// <summary>
    /// A query for the thrift call get_slice
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <typeparam name="N"></typeparam>
    /// <typeparam name="V"></typeparam>
    public class ThriftSliceQuery<K,N,V> : AbstractSliceQuery<K, N, V, ColumnSlice<N, V>>, SliceQuery<K, N, V>
    {
        public ThriftSliceQuery(Keyspace k, Serializer<K> keySerializer,
            Serializer<N> nameSerializer, Serializer<V> valueSerializer) :
            base(k, keySerializer, nameSerializer, valueSerializer)
        {
        }
        public K Key
        {
            get;
            set;
        }
        public SliceQuery<K, N, V> SetKey(K key)
        {
            Key = key;
            return this;
        }
        public override string ToString()
        {
            return "SliceQuery(" + Key + "," + ToStringInternal() + ")";
        }
        public new SliceQuery<K, N, V> SetColumnNames(List<N> columnNames) 
        {
            return (SliceQuery<K, N, V>) base.SetColumnNames(columnNames);
        }
        public new SliceQuery<K, N, V> SetRange(N start, N finish, bool reversed, int count)
        {
            return (SliceQuery<K, N, V>) base.SetRange(start, finish, reversed, count);
        }
        public new SliceQuery<K, N, V> SetColumnFamily(string cf)
        {
            return (SliceQuery<K, N, V>) base.SetColumnFamily(cf);
        }
        public override QueryResult<ColumnSlice<N, V>> Execute() 
        {
            Func<KeyspaceService, ColumnSlice<N, V>> x = (KeyspaceService ks) =>
            {
                ColumnParent columnParent = new ColumnParent(ColumnFamilyName);
                List<Column> thriftRet = ks.GetSlice(KeySerializer.ToBytes(Key), columnParent, GetPredicate());
                return new ColumnSliceImpl<N,V>(thriftRet, ColumnNameSerializer, ValueSerializer);
            };
            return new QueryResultImpl<ColumnSlice<N, V>>(
                Keyspace.DoExecute(new KeyspaceOperationCallbackBuilder<ColumnSlice<N, V>>(x)), this);
        }
    }
}
